﻿using Microsoft.Extensions.Caching.Memory;
using YiSha.Core.Cache;

namespace YiSha.Core.DynamicData;

public class CacheEntity : ICacheEntity
{
    public const string tableKey = "2f29bb513fca3003cbd8e1199cc7b114";
    public const string menuKey = "f8b818b283d6cca7893472a7f178c56c";
    private readonly IFreeSql _freeSql;
    private readonly IMemoryCache _memoryCache;
    private readonly ISignal _signal;
    public CacheEntity(IFreeSql freeSql, IMemoryCache memoryCache, ISignal signal)
    {
        _freeSql = freeSql;
        _memoryCache = memoryCache;
        _signal = signal;
    }

    public IList<OriginalTable>? GetOriginalTables()
    {
        return _memoryCache.GetOrCreate(tableKey, (entry) =>
        {
            entry.ExpirationTokens.Add(_signal.GetToken(tableKey));
            var tables = _freeSql.Select<OriginalTable>().ToList();
            var properties = GetOriginalProperties();
            foreach (var table in tables)
            {
                table.Properties = properties.Where(a => a.TableId == a.TableId).ToList();
            }
            return tables ?? new List<OriginalTable>();
        });

    }
    private IList<OriginalProperty> GetOriginalProperties()
    {
        var items = _freeSql.Select<OriginalProperty>().ToList();
        return items;
    }
    public IList<ControlMenu>? GetControlMenus()
    {
        return _memoryCache.GetOrCreate(menuKey, (entry) =>
        {
            entry.ExpirationTokens.Add(_signal.GetToken(tableKey));
            var tables = _freeSql.Select<ControlMenu>().ToList();
            return tables ?? new List<ControlMenu>();
        });
    }
    public OriginalTable GetOriginalTable(int menuId)
    {
        var menu = GetControlMenus()?.FirstOrDefault(a => a.Id == menuId);
        var table = GetOriginalTables()?.FirstOrDefault(a => a.Id == menu?.TableId);
        return table ?? new OriginalTable();
    }
}
